package cn.edu.ctgu.ch3;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * @author tiger54910
 * @create 2025/2/3 11:50
 */
@Slf4j
public class HttpCallTry {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public String getId() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://external-service/resouce");
        Try<HttpResponse> response = Try.of(() -> client.execute(httpGet));
        return response
                .mapTry(this::extractStringBody)
                .mapTry(this::toEntity)
                .map(this::extractUserId)
                .onFailure(ex -> log.error("The getId() failed.", ex))
                .getOrElse("DEFAULT_ID");
    }

    private String extractUserId(EntityObject entityObject) {
        return entityObject.id;
    }

    private String extractStringBody(HttpResponse response) throws IOException {
        return new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)
        ).lines().collect(Collectors.joining("\n"));
    }

    private EntityObject toEntity(String content) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(content, EntityObject.class);
    }
    private static class EntityObject {
        String id;

        public EntityObject(String id) {
            this.id = id;
        }
    }
}
